package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginRequired;
import com.alibaba.fastjson.JSON;
import javassist.util.proxy.MethodHandler;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Reference
    private IUserInfoCacheService userInfoCacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //静态资源直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //session里面有没有
        if (request.getSession().getAttribute(Consts.USER_INFO) != null) {
            return true;
        }
        //redis里面有没有
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (Consts.USER_INFO_TOKEN.equals(cookie.getName())) {
                    String userInfo = userInfoCacheService.getUserInfo(cookie.getName());
                    if (userInfo != null) {
                        //有的话存到本地session
                        UserInfo parseObject = JSON.parseObject(userInfo, UserInfo.class);
                        request.getSession().setAttribute(Consts.USER_INFO, parseObject);
                        return true;
                    }
                }
            }
        }
        //有没有注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.hasMethodAnnotation(LoginRequired.class)) {
            //判断有无ResponseBody注解
            if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
                //有的话就是异步请求,获取流返回一个JSON字符串
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.mark("请先登录");
                ajaxResult.setCode(AjaxResult.CODE);
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(ajaxResult));
            } else {
                response.sendRedirect("/login.html");
            }
            return false;
        } else {
            return true;
        }
    }
}
